package jflowmap.views.heatmap;

import java.awt.BasicStroke;
import java.awt.Color;
import java.awt.Font;
import java.awt.Stroke;
import java.awt.geom.Rectangle2D;
import java.util.List;

import jflowmap.model.graph.Node;
import jflowmap.model.ontology.Dimension;
import jflowmap.model.ontology.SelectionListener;

import com.google.common.collect.Lists;

import edu.umd.cs.piccolo.PNode;
import edu.umd.cs.piccolo.nodes.PPath;
import edu.umd.cs.piccolo.nodes.PText;

public class Sink extends PPath implements SelectionListener {
	private final static Font CAPTION_FONT = new Font("Arial", Font.PLAIN, 10);
	private final static Stroke BORDER_STROKE = new BasicStroke(1);
	
	private final Node node;
	private final VisualHeatMap visualHeatMap;
	private final PText caption;
	private final List<Sink> parentSinks = Lists.newLinkedList();
	private BarChart barChart;
	
	public Sink(Node source, VisualHeatMap visualHeatMap) {
		this.node = source;
		this.visualHeatMap = visualHeatMap;
		
		this.caption = new PText(node.getName());
		this.caption.setFont(CAPTION_FONT);
		
		this.setBounds(0, 0, caption.getWidth() + 20, caption.getHeight() + 4);

		this.addChild(caption);
		caption.setX(20);
		caption.setY(4);
		
		visualHeatMap.getHeatMapView().getView().getSelection("standard")
		.addSelectionListener(node.getDimension(), this);
	}

	public void setMaxWidth(final double maxWidth) {
		this.setPathTo(new Rectangle2D.Double(0, 0, maxWidth, caption.getHeight() + 8));
		this.setStroke(BORDER_STROKE);
		caption.setX(20 + (maxWidth-40)/2 - caption.getWidth()/2);
		
		if (this.barChart != null) this.removeChild(barChart);
		this.barChart = new BarChart(node, visualHeatMap.getGraph(), visualHeatMap.getHeatMapView().getView(), maxWidth-30);
		barChart.setOffset(10, caption.getHeight() + 10);
	
		if (visualHeatMap.getHeatMapView().getView().getSelection("standard")
				.isSelected("SOURCE", node.getDimension())) {
			this.select("SOURCE", node.getDimension());
		}
	}

	public Node getNode() {
		return node;
	}

	@Override
	public void select(String category, Dimension dimension) {
		if ("SOURCE".equals(category)) {
			this.setPaint(Color.CYAN);
			this.addChild(barChart);
			this.setHeight(caption.getHeight() + 16 + BarChart.MAX_HEIGHT);
		}
	}

	@Override
	public void unselect(String category, Dimension dimension) {
		if ("SOURCE".equals(category)) {
			this.setPaint(Color.WHITE);
			this.removeChild(barChart);
			this.setHeight(caption.getHeight() + 8);
		}	
	}

	public void update() {
		this.barChart.update();
	}

	@Override
	public void dispose() {
		visualHeatMap.getHeatMapView().getView().getSelection("standard")
		.removeSelectionListener(node.getDimension(), this);
	}
}
